<template>
  <div class="container">
    <div class="main">
      <div class="main_content">
        <div class="main_header">
          <a-input
            placeholder="搜索题目详情"
            style="width: 160px; height: 36px"
            v-model="searchDetail"
          />
          <a-button
            type="primary"
            style="margin-left: 10px; width: 70px; height: 36px"
            @click="toSearch"
            :disabled="!isAuth(['ROOT', 'QUESTION:SELECT'])"
          >
            查询
          </a-button>
          <a-button
            type="primary"
            style="margin-left: 10px; width: 70px; height: 36px"
            @click="toAdd"
            v-if="isAuth(['ROOT', 'QUESTION:INSERT'])"
          >
            新增
          </a-button>
          <a-popconfirm
            :disabled="!isAuth(['ROOT', 'QUESTION:DELETE'])"
            title="是否进行批量删除"
            ok-text="确认"
            cancel-text="取消"
            @confirm="confirm2"
            @cancel="cancel2"
          >
            <a-button
              v-if="isAuth(['ROOT', 'QUESTION:DELETE'])"
              type="danger"
              style="margin-left: 10px; width: 98px; height: 36px"
            >
              批量删除
            </a-button>
          </a-popconfirm>
        </div>
        <a-spin
          size="large"
          v-show="loadingVisible"
          style="loading_icon"
          tip="正在加载中"
        ></a-spin>
        <div class="main_table">
          <!-- data-source 数据源,column 列名  row-selection列表项是否可选择	-->
          <!-- rowSelection 是计算属性进行加工处理 -->
          <a-table
            rowKey="id"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }"
            :columns="columns"
            :data-source="data"
            :pagination="pagination"
            @change="handleTableChange"
          >
            <!-- 作用域插槽 text 本身是每一列的所有属性 但是 column的配置是 dataIndex 是avaurl 所以text 就变成了每一类的avarurl -->
            <span slot="choice" slot-scope="record">
              <ul>
                <li v-for="(val, keys, i) in record.options" :key="i">
                  {{ keys }} : {{ val }}
                </li>
              </ul>
            </span>

            <span slot="action" slot-scope="text, record">
              <a
                @click="modifyItem(record)"
                v-if="isAuth(['ROOT', 'QUESTION:UPDATE'])"
              >
                修改</a
              >
              <a-divider
                type="vertical"
                v-if="isAuth(['ROOT', 'QUESTION:UPDATE'])"
              />
              <a-popconfirm
                title="请确定是否删除该分类题型"
                ok-text="确定"
                cancel-text="取消"
                @confirm="deleteItem(record)"
                @cancel="cancel(record)"
                :disabled="!isAuth(['ROOT', 'QUESTION:DELETE'])"
              >
                <!-- 如果学生的disableColor -->
                <a href="#" v-if="isAuth(['ROOT', 'QUESTION:DELETE'])">
                  删除
                </a>
              </a-popconfirm>
            </span>
          </a-table>
        </div>
      </div>
    </div>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getRoleMessage"
    ></add-or-update>
  </div>
</template>
<script>
import AddOrUpdate from "../components/questionsDetail-add-or-update.vue";
export default {
  components: {
    AddOrUpdate,
  },
  data() {
    return {
      selectedRowKeys: [], // Check here to configure the default column
      loadingVisible: true,
      idList: [],
      // 搜索框内容
      searchDetail: "",
      // 静态模态的出现
      addOrUpdateVisible: false,
      // 列名
      columns: [
        // title:列名; dataIndex: 对应数据源中的键值(kay)
        {
          title: "创建者",
          dataIndex: "creator",
        },
        {
          title: "题库分类",
          dataIndex: "category",
        },
        {
          title: "题库类型",
          dataIndex: "type",
        },
        {
          title: "题目详情",
          dataIndex: "content",
          width: 150,
        },
        {
          title: "题目难度",
          dataIndex: "level",
        },
        {
          title: "题目选项",
          key: "choice",
          scopedSlots: { customRender: "choice" },
          width: 200,
        },
        {
          title: "题目答案",
          dataIndex: "answers",
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" },
        },
      ],
      // 数据源
      data: [
        //  键值key 对应列名, key为Vue 需要key 可以忽略
      ],
      pagination: {
        defaultPageSize: 5, // 默认当前页数
        defaultPageSize: 5, // 默认当前页显示数据的大小
        position: "bottom",
        pageSize: 10,
        pageSizeOptions: ["10", "15", "20", "25"],
        current: 1,
        total: 0,
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
      },
      //   表头的配置条件
      sortedInfo: null,
    };
  },
  created() {
    this.searchRole();
  },
  methods: {
    // 设置 用户选中之后的回调
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed:123 ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      let ids = [];
      selectedRowKeys.forEach((item) => {
        ids.push(item);
      });
      this.idList = ids;
    },
    modifyItem(record) {
      // this.addOrUpdateVisible = true;
      this.$router.push({
        name: "questionsAddPage",
        params: { record },
      });
    },
    // 查询用户
    async toSearch() {
      this.loadingVisible = true;
      if (this.searchDetail == "") {
        this.getRoleMessage();
      } else {
        const { data: res } = await this.$http.get(
          `/admin/questions?content=${this.searchDetail}`
        );
        this.loadingVisible = false;
        this.pagination.total = Number(res.data.total);
        let tmpdata = res.data.records;
        tmpdata.forEach((item) => {
          if (item.type == 1) {
            item.type = "单选题";
          } else if (item.type == 2) {
            item.type = "多选题";
          } else {
            item.type = "判断题";
          }
        });
        this.data = tmpdata;
      }
    },
    toAdd() {
      // this.addOrUpdateVisible = true;
      // this.$nextTick(() => {
      //   this.$refs.addOrUpdate.init();
      //   // 清空表单 发送请求 获取表单项的部分选择数据.
      // });
      this.$router.push({
        name: "questionsAddPage",
      });
    },
    async deleteItem(item) {
      this.loadingVisible = true;
      let ids = [item.id];
      const { data: res } = await this.$http.delete("/admin/questions", {
        data: {
          ids: ids,
        },
      });
      if (res.code == 200) {
        this.common.notify("success", "删除成功");
        this.selectedRowKeys = this.selectedRowKeys.filter((target) => {
          return target != item.id;
        });
        this.idList = this.selectedRowKeys;
        this.pagination.current = 1;
        // this.$message.success("删除成功");
        this.getRoleMessage();
      } else {
        this.common.notify("warning", "删除失败");
        this.loadingVisible = false;
      }
    },
    // 分页点击切换
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      let that = this;
      that.sortedInfo = sorter;
      // 通过点击 点击 改变current 中的属性 再影响pagination
      const pager = { ...that.pagination };
      pager.current = pagination.current;
      that.pagination = pager;
      this.searchRole();
    },

    // 分页查询
    async getRoleMessage(val) {
      this.searchRole();
    },
    // 分页查询显示
    async searchRole() {
      const { data: res } = await this.$http.get(
        `/admin/questions?page=${this.pagination.current}&size=${this.pagination.pageSize}`
      );
      this.loadingVisible = false;
      this.pagination.total = Number(res.data.total);
      let tmpdata = res.data.records;
      tmpdata.forEach((item) => {
        if (item.type == 1) {
          item.type = "单选题";
        } else if (item.type == 2) {
          item.type = "多选题";
        } else {
          item.type = "判断题";
        }
      });
      this.data = tmpdata;
    },
    // 批量删除按钮 确认弹框
    confirm2(e) {
      this.mutiDelete();
    },
    // 批量删除按钮 取消弹框
    cancel2() {},

    // 批量删除
    async mutiDelete() {
      this.loadingVisible = true;
      const { data: res } = await this.$http.delete("/admin/questions", {
        data: {
          ids: this.idList,
        },
      });
      if (res.code == 200) {
        this.common.notify("success", "删除成功");
        // 将删除的元素 从selectedRowKeys中过滤出去
        this.idList.forEach((target) => {
          this.selectedRowKeys = this.selectedRowKeys.filter((item) => {
            return item != target;
          });
        });
        this.idList = this.selectedRowKeys;
        this.pagination.current = 1;
        // this.$message.success("删除成功");
        this.getRoleMessage();
      } else {
        this.loadingVisible = false;
        this.common.notify("warning", "无法删除,请重新选择");
        // this.$message.warning("无法删除,请重新选择");
      }
    },
  },
  computed: {
    //   表格选中的配置项
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          let ids = [];
          selectedRows.forEach((item) => {
            ids.push(item.id);
          });
          this.idList = ids;
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.name === "Disabled User", // Column configuration not to be checked
            name: record.name,
          },
        }),
      };
    },
  },
};
</script>
<style  lang='less' scoped>
.container {
  box-sizing: border-box;
  display: flex;
  background-color: #eef1f2;
  // overflow: scroll;
  padding: 35px 75px;

  .main {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-items: center;
    // overflow: scroll;
    background-color: #eef1f2;
    // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    .main_content {
      padding: 20px;
      padding-top: 20px;
      width: 100%;
      height: 100%;
      background-color: #fff;
      border-radius: 10px;
      .main_header {
        display: flex;
        margin-bottom: 25px;
        .main_table {
          margin-top: 50px;
        }
      }
    }
  }
}
/deep/ .ant-table-thead > tr > th,
.ant-table-tbody > tr > td {
  text-align: center;
}
/deep/ .ant-table-tbody > tr > td {
  text-align: left !important;
}
.disableColor {
  color: #eee;
}
li {
  list-style: none;
  margin-top: 10px;
}

/deep/ .ant-spin-spinning {
  z-index: 100;
  position: absolute;
  top: 50%;
  left: 55%;
}
</style>